package weaver.splittable.biz.workflow;

import weaver.conn.WeaverConnection;
import weaver.conn.WeaverStatement;
import weaver.splittable.STConfig;
import weaver.splittable.db.STDBSupport;
import weaver.splittable.db.STDBUtil;

import java.sql.SQLException;
import java.util.Map;

public class STWorkflowCreateTableUtil {

    public static void initSTWorkflowTables(WeaverConnection connection) throws SQLException {

        WeaverStatement statement = (WeaverStatement) connection.createStatement();

        for (Map.Entry<String, String> entry: STWorkflowConstants.SPLIT_TABLES.entrySet()) {
            String tableName = entry.getKey();
            String tableDataId = entry.getValue();

            String createFullDataTableSQL = STDBUtil.createFullDataTable(tableName);
            if (createFullDataTableSQL != null) {
                statement.originExecuteUpdate(createFullDataTableSQL);
            }
        }

        statement.close();
    }

    public static boolean isCreatedFullDataTables(WeaverConnection connection) throws SQLException {
        boolean isCreatedFullDataTables = true;
        WeaverStatement statement = (WeaverStatement) connection.createStatement();
        for (String tableName: STWorkflowConstants.SPLIT_TABLES.keySet()) {
            String fullDataTableName = tableName + "_all";
            if (STDBSupport.ORACLE.equals(STConfig.DB_TYPE)) {
                fullDataTableName = fullDataTableName.toUpperCase();
            }
            boolean tableIsExist = STDBUtil.checkTableIsExist(tableName, connection);
            isCreatedFullDataTables = isCreatedFullDataTables && tableIsExist;
        }
        statement.close();
        return isCreatedFullDataTables;
    }
}
